<script setup>
import {
  addUser,
  deleteUser,
  updateUserApi,
  queryUser,
  queryUserTree,
  unLock,
  resetPwdByAdmin,
  updateOrgManager,
  searchTree
} from '@/api/system/user'
import { findOrgTree, findDescendant, orgDelete } from '@/api/collection/orgManagement'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, ArrowDown } from '@element-plus/icons-vue'
import { usePagination } from '@/hooks/usePagination'
import { sm4Encrypt } from '@/utils/sm4'
import AddUser from './components/AddUser.vue'
import ResetPwd from './components/ResetPwd.vue'
import UpdateOrg from './components/UpdateOrg.vue'

const loading = ref(false)
const orgLoading = ref(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const addUserRef = ref(null)
const resetPwdRef = ref(null)
const updateOrgRef = ref(null)
const pageData = reactive({
  isShowAddDialog: false,
  isShowResetDialog: false,
  isShowOrgDialog: false,
  editingId: ''
})

const filterText = ref('')
const treeRef = ref()
const scrollbarRef = ref()
const treeData = ref([])
const baseTreeData = ref([])

watch(filterText, (val) => {
  if (val) {
    searchTree(val).then((res) => {
      treeData.value = getData(res.data)
    })
  } else {
    treeData.value = baseTreeData.value
  }
  // treeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

const toAddUser = () => {
  const currentKey = treeRef.value.getCurrentNode().code
  console.log(currentKey)
  if (currentKey) {
    pageData.isShowAddDialog = true
    pageData.editingId = ''
  } else {
    ElMessage({
      message: '请先选择组织',
      type: 'warning',
      duration: 5 * 1000
    })
  }
}

const createUser = (record) => {
  record.password = sm4Encrypt(record.password)
  addUser({
    orgCode: treeRef.value.getCurrentNode().code,
    ...record
  })
    .then(() => {
      ElMessage.success('新增成功')
      pageData.isShowAddDialog = false
      getTableData()
    })
    .finally(() => {
      addUserRef.value.submitBtnLoading = false
    })
}

const updateUser = (record) => {
  updateUserApi({
    id: pageData.editingId,
    ...record
  })
    .then(() => {
      ElMessage.success('修改成功')
      pageData.isShowAddDialog = false
      getTableData()
    })
    .finally(() => {
      addUserRef.value.submitBtnLoading = false
    })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteUser(row._id).then(() => {
      ElMessage.success('删除成功')
      getTableData()
    })
  })
}

const handleUpdate = (row) => {
  pageData.editingId = row._id
  pageData.isShowAddDialog = true
}

const tableData = ref([])
const searchFormRef = ref()
const searchData = reactive({
  username: ''
})
const getTableData = () => {
  loading.value = true
  const currentKey = treeRef.value?.getCurrentNode()?.code
  const param = {
    ...searchData,
    orgCode: currentKey ?? ''
  }
  queryUser(param, {
    currentPage: (paginationData.currentPage - 1) * paginationData.pageSize,
    size: paginationData.pageSize
  })
    .then((res) => {
      paginationData.total = parseInt(res.data.total)
      tableData.value = res.data.data
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  filterText.value = ''
  treeRef.value?.setCurrentKey(null)
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

const currentChange = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}

// 重置密码
const showResetDialog = (record) => {
  pageData.editingId = record.id
  pageData.isShowResetDialog = true
}
const resetSave = (record) => {
  resetPwdByAdmin({
    password: sm4Encrypt(record.password),
    id: pageData.editingId
  })
    .then(() => {
      ElMessage.success('重置成功')
      pageData.isShowResetDialog = false
    })
    .finally(() => {
      resetPwdRef.value.submitBtnLoading = false
    })
}
// 解锁账号
const unlockAccount = async (record) => {
  await unLock({ id: record.id })
  ElMessage.success('解锁成功')
  getTableData()
}
// 修改组织
const showOrgDialog = (record) => {
  pageData.editingId = record.id
  pageData.isShowOrgDialog = true
}
const orgSave = async (sysOrgManagerId) => {
  const param = {
    id: pageData.editingId,
    sysOrgManagerId
  }
  updateOrgManager(param)
    .then(() => {
      ElMessage.success('修改组织成功')
      pageData.isShowOrgDialog = false
      getTableData()
    })
    .finally(() => {
      updateOrgRef.value.submitBtnLoading = false
    })
}

const queryOrg = () => {
  const param = {
    name: ''
  }
  orgLoading.value = true
  findOrgTree(param)
    .then((res) => {
      treeData.value = getData(res.data)
      baseTreeData.value = getData(res.data)
    })
    .finally(() => {
      orgLoading.value = false
    })
}
const loadNode = (node, resolve) => {
  if (node.level == 0) {
    resolve(node.data)
  } else {
    if (node.data.children && node.data.children.length > 0) {
      resolve(node.data.children)
    } else {
      findDescendant(node.data.code).then((res) => {
        resolve(getData(res.data))
      })
    }
  }
}
const getData = (data) => {
  if (data.length) {
    data.forEach((item) => {
      if (item.children && item.children.length > 0) {
        item.children = getData(item.children)
      }
      item.isLeaf = item.type == 'ORGANIZATION' ? false : true
    })
    return data
  } else {
    return []
  }
}
queryOrg()
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <div class="flex">
      <el-card class="mr-6 w-1/4" v-loading="orgLoading">
        <div>
          <el-input v-model="filterText" :prefix-icon="Search" placeholder="搜索组织名称" clearable />
          <el-scrollbar ref="scrollbarRef" height="80vh">
            <el-tree
              ref="treeRef"
              class="filter-tree mt-4"
              :data="treeData"
              node-key="id"
              :props="{ label: 'name', isLeaf: 'isLeaf' }"
              :filter-node-method="filterNode"
              lazy
              :load="loadNode"
              @current-change="currentChange"
              highlight-current
              check-strictly
              :render-after-expand="false"
            />
          </el-scrollbar>
        </div>
      </el-card>
      <el-card class="flex-grow w-3/4">
        <div>
          <div shadow="never" class="search-wrapper">
            <el-form ref="searchFormRef" :inline="true" :model="searchData">
              <el-form-item prop="username" label="用户账号">
                <el-input v-model="searchData.username" placeholder="请输入用户账号" maxlength="30" clearable />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
                <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div v-loading="loading" shadow="never">
            <div class="toolbar-wrapper">
              <div>
                <el-button type="primary" plain :icon="Plus" @click="toAddUser">新增用户</el-button>
              </div>
            </div>
            <div class="table-wrapper">
              <el-table :data="tableData" max-height="64vh">
                <el-table-column fixed prop="username" label="用户账号" min-width="120" align="center" />
                <el-table-column fixed prop="name" label="昵称" min-width="120" align="center" />
                <el-table-column prop="orgName" label="所属组织" min-width="150" align="center" />
                <el-table-column label="操作" min-width="150" align="center">
                  <template #default="scope">
                    <div class="">
                      <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                      <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
                      <!-- <el-dropdown class="operation-more">
                        <span class="el-dropdown-link">
                          更多
                          <el-icon class="el-icon--right">
                            <arrow-down />
                          </el-icon>
                        </span>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="showResetDialog(scope.row)">
                              <div class="dropdown-item">重置密码</div>
                            </el-dropdown-item>
                            <el-dropdown-item v-hasPermi="['sysUser:post:unLock']" @click="unlockAccount(scope.row)">
                              <div class="dropdown-item">解锁账号</div>
                            </el-dropdown-item>
                            <el-dropdown-item
                              v-hasPermi="['sysUser:put:updateOrgManager']"
                              @click="showOrgDialog(scope.row)"
                            >
                              <div class="dropdown-item">修改组织</div>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown> -->
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="flex justify-end">
              <el-pagination
                background
                :layout="paginationData.layout"
                :page-sizes="paginationData.pageSizes"
                :total="paginationData.total"
                :page-size="paginationData.pageSize"
                :currentPage="paginationData.currentPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :small="true"
              />
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <AddUser
      ref="addUserRef"
      v-model:visible="pageData.isShowAddDialog"
      :id="pageData.editingId"
      @create="createUser"
      @update="updateUser"
    />
    <ResetPwd ref="resetPwdRef" v-model:visible="pageData.isShowResetDialog" @save="resetSave" />
    <UpdateOrg ref="updateOrgRef" v-model:visible="pageData.isShowOrgDialog" @save="orgSave" />
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;

  :deep(.el-button) {
    padding: 6px 12px;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}

.operation-more {
  margin-left: 12px;
  font-size: 12px;

  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
  }
}
:deep(.el-dropdown-menu__item) {
  padding: 0;
}
.dropdown-item {
  padding: 5px 16px;
}
</style>
